package com.hjl.cn.controller;

import com.hjl.cn.config.wxconfig.WxPayConfig;
import com.hjl.cn.service.WxPayService;
import com.hjl.cn.utils.QRCodeUtil;
import com.hjl.cn.utils.ReturnResult;
import com.hjl.cn.utils.ReturnResultUtils;
import com.hjl.cn.utils.WxPayUtils;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

/**
 * @author jialin
 * @createTime 2020-09-26
 */
@Log4j
@RestController
@RequestMapping(value = "/wxPay")
public class WxPayController {

    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private WxPayConfig wxPayConfig;

    //https://6a3c5f804b5a.ngrok.io/wxPay/getCodeUrl
    @GetMapping(value = "/getCodeUrl")
    public String getCodeUrl() throws Exception {
        String str = wxPayService.unifiedOrder();
        System.out.println();
        return "1";
    }

    //https://6a3c5f804b5a.ngrok.io/wxPay/notifyUrl
    @RequestMapping(value = "/notifyUrl")
    public void notifyUrl(HttpServletRequest request, HttpServletResponse response) throws Exception {
        InputStream inputStream = request.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        StringBuffer stringBuffer = new StringBuffer();
        String line;
        while (null != (line = bufferedReader.readLine())) {
            stringBuffer.append(line);
        }
        bufferedReader.close();
        inputStream.close();
        //xml格式转换map
        Map<String, String> resultMap = WxPayUtils.xmlToMap(stringBuffer.toString());
        //验证签名
        if (WxPayUtils.checkSign(resultMap, wxPayConfig.getKey())) {
            String resultCode = resultMap.get("result_code");
            PrintWriter writer = response.getWriter();
            //支付成功，商户处理后同步返回给微信参数
            if ("SUCCESS".equals(resultCode)) {
                //支付成功的业务
                String noticeStr = setXML("SUCCESS", "OK");
                writer.write(noticeStr);
                writer.flush();
                System.out.println("===支付成功！===");
            } else {
                String noticeStr = setXML("FAIL", "FAIL");
                writer.write(noticeStr);
                writer.flush();
                System.out.println("===支付失败！===");
            }
        }
    }

    public static String setXML(String return_code, String return_msg) {
        return "<xml><return_code><![CDATA[" + return_code + "]]></return_code><return_msg><![CDATA[" + return_msg + "]]></return_msg></xml>";
    }
}







